const Router = require('koa-router')
const auth = require('../../middleware/auth')
const {User,Group,UserFavor} = require('../../model/index')

const { Success, CustomError } = require('../../core/common')
const {ParameterError}=require("../../config/errorCode")

const router = new Router({
  prefix: '/v1/user'
})
//获取用户信息
router.get("/getUserInfo",auth,async ctx=>{
  const {user}=ctx.auth
  Success(ctx,user.toJSON())
})
// 获取用户详细信息
router.get("/getUserInfoDetail",auth,async ctx=>{
  const {user}=ctx.auth
  const userBlogCount=await user.countBlogs()
  const favorCount=await user.countFollow()
  const beFavorCount=await user.countUser()
  Success(ctx,{
    userBlogCount,
    favorCount,
    beFavorCount
  })
})
//修改用户信息
router.put("/modifyUserInfo",auth,async ctx=>{
  const {avatar,nickName}=ctx.request.body
  const {user}=ctx.auth
  //如果要修改昵称
  if(user.nickName!=nickName){
    const nickNameUser = await User.findOne({ where: { nickName } })
    if (nickNameUser) {
        throw new CustomError('改昵称已注册', ParameterError)
    }
  }
  user.avatar=avatar
  user.nickName=nickName
  const _modifyItem=await user.save()
  console.log("_modifyItem",_modifyItem)
  Success(ctx,user.userInfo)
})
//修改密码
router.put("/modifyPassword",async ctx=>{
  const {phone,password:newPassword}=ctx.request.body
  const user=await User.findOne({
    where:{
      phone
    }
  })
  if(user){
    user.password=newPassword
    const newPasswordUser=await user.save()
    if(newPasswordUser){
      Success(ctx,"修改成功")
    }
  }
  else{
    throw new CustomError("该手机号尚未注册",ParameterError)
  }
})
// 获取分组
router.get('/getGroup', auth, async (ctx) => {
  const { user } = ctx.auth
  const groupList = await user.getGroups()
  const groupListJson = groupList.map(item => item.toJSON())
  const result = {
    defaultGroup: groupListJson.filter(item => item.type == 1),
    myGroup: groupListJson.filter(item => item.type == 2)
  }
  Success(ctx, result)
})

// 添加分组
router.post('/addGroup', auth, async (ctx) => {
  const { user } = ctx.auth
  const { name } = ctx.request.body
  const groups=await user.getGroups()
  const myGroups=groups.filter(group=>group.type==2)
  const group=myGroups.find(group=>group.name==name)
  if(group){
      throw new CustomError("该分组已存在",ParameterError)
  }
  const addGroupItem = await user.createGroup({ name, type: 2, canDel: true })
  Success(ctx, addGroupItem.toJSON())
})

//删除分组
router.del('/delGroup', auth, async (ctx) => {
    const {user}=ctx.auth
    const {key}=ctx.request.body
    console.log("key is",key)
    const groups=await user.getGroups()
    const delItem=groups.find(group=>group.key==key)
    if(delItem){
        const _delItem=await user.removeGroup(delItem)
        console.log("delItem----------",_delItem)
        await delItem.destroy();
        Success(ctx,"ok")
    }
    else{
        throw new CustomError("该分组不存在",ParameterError)
    }
})
//
module.exports = router
